const util = require('../../../../../utils/util.js');
const api = require('../../../../../config/api.js');
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    logininfo: {},
    noticeLength: 0,
  },
  //打开选择地址组件
  openAddrPicker: function () {
    var _this = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          // 未授权
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              _this.albumInfoPositionStart();
            },
            fail: function () {
            }
          })
        } else {
          // 已授权
          _this.albumInfoPositionStart();
        }
      }
    })
  },
  /**
   * 位置
   */
  albumInfoPositionStart: function () {
    var _this = this;
    wx.chooseLocation({
      success: function (res) {
        var value = res.name;
        var latitude = res.latitude;
        var longitude = res.longitude;
        var address = res.address;
        if (value != null && value.length > 0) {
          var openid = app.globalData.logininfo.openid
          var data = {}
          if (openid != null && openid != "") {
            util.post(api.fetchToken()).then(function (res) {
              if (res.access_token != '') {
                return Promise.resolve({
                  access_token: res.access_token
                });
              }
            }).then(function (res) {
              var access_token = res.access_token;
              let param = {};
              param = {
                "openid": app.globalData.logininfo.openid,
                "addr": value,
                "latitude": latitude,
                "longitude": longitude,
                "address": address
              };
              data.openid = openid
              let url = api.My_doUpdateStoreInfo + "?access_token=" + access_token;
              util.request(url, param, 'POST').then(function (res) {
                if (res.code == 200) {
                  console.log(res)
                }
              });
            });
          }
          _this.data.logininfo.storeInfo.addr = value;
          _this.data.logininfo.storeInfo.latitude = latitude;
          _this.data.logininfo.storeInfo.longitude = longitude;
          _this.data.logininfo.storeInfo.address = address;
          wx.setStorage({
            key: 'logininfo',
            data: _this.data.logininfo
          });
        } else {
          util.dialogAlert("未选中有效地址")
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      logininfo: app.globalData.logininfo,
      openid: app.globalData.logininfo.openid
    });

    //计算店铺公告长度
    if (this.data.logininfo.storeInfo.storeremark != null && this.data.logininfo.storeInfo.storeremark!=''){
      if (this.data.logininfo.storeInfo.storeremark.length != 0) {
        let content = this.data.logininfo.storeInfo.storeremark.length;
      } else {
        let content = 0;
      }
      this.setData({
        noticeLength: content
      });
      console.log(this.data.noticeLength)
    }
  },

  dostoreremark: function (event) {
    this.setData({
      noticeLength: event.detail.value.length
    });
    console.log(this.data.noticeLength)
  },
  doupdatedname: function (event){
    var _this = this;

    let akind = event.currentTarget.dataset.name;
    let updatename = event.detail.value;

    let atitle = '';
    let param = {};
    if (akind == 'storename') {
      atitle = '修改店铺名';
      param = {
        "openid": app.globalData.logininfo.openid,
        "storename": updatename
      };
    }
    else if (akind == 'nickname') {
      atitle = '修改用户昵称';
      param = {
        "openid": app.globalData.logininfo.openid,
        "nickname": updatename
      };
    }

    wx.showLoading({
      title: atitle,
    })

    util.post(api.My_fetchTokenUrl).then(function (res) {
      if (res.access_token != '') {
        return Promise.resolve({
          access_token: res.access_token
        });
      }
    }).then(function (res) {
      //console.log("res:" + res.accesstoken);

      if (res.access_token != '') {
        _this.setData({
          accesstoken: res.access_token
        });

        let url = api.My_doUpdatePersonInfo + "?access_token=" + _this.data.accesstoken;
        util.request(url, param, 'POST').then((res2) => {
          console.log(res2);

          if (akind == 'storename') {
            _this.data.logininfo.userInfo.storename = updatename;
          }
          else if (akind == 'nickname') {
            _this.data.logininfo.userInfo.nickName = updatename;
          }

          wx.setStorage({
            key: 'logininfo',
            data: _this.data.logininfo
          });

          wx.hideLoading();
        }).catch((err) => {
          wx.hideLoading();

          console.log(err);
          console.log("保存信息错误!");
        });
      }
      else {
        console.log("error accesstoken!");
      }
    }).catch((err) => {
      wx.hideLoading();

      console.log(err);
    });
  },
  doupdatename: function (event) {
    var _this = this;
    var openUpdate = true;
    let akind = event.currentTarget.dataset.name;
    let updatename = event.detail.value.replace(/\s+/g, '');
    let atitle = '';
    let param = {};
    if (akind == 'storefullname') {
      atitle = '修改店铺全称';
      param = {
        "openid": app.globalData.logininfo.openid,
        "storefullname": updatename
      };
    }
    else if (akind == 'zipcode') {
      atitle = '修改邮编';
      param = {
        "openid": app.globalData.logininfo.openid,
        "zipcode": updatename
      };
    }
    else if (akind == 'addr') {
      atitle = '修改地址';
      param = {
        "openid": app.globalData.logininfo.openid,
        "addr": updatename
      };
    }
    else if (akind == 'mastername') {
      atitle = '修改负责人姓名';
      param = {
        "openid": app.globalData.logininfo.openid,
        "mastername": updatename
      };
    }
    else if (akind == 'jobtitle') {
      atitle = '修改职位';
      param = {
        "openid": app.globalData.logininfo.openid,
        "jobtitle": updatename
      };
    }
    else if (akind == 'mobile') {
      if (!(/^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/.test(updatename))) {
        wx.showToast({
          title: '手机号码有误',
          duration: 2000,
          icon: 'none'
        });
        openUpdate = false
      } else {
        atitle = '修改手机';
        param = {
          "openid": app.globalData.logininfo.openid,
          "mobile": updatename
        };
        console.log(111111)
      }
    }
    else if (akind == 'storeremark') {
      atitle = '修改店铺公告';
      param = {
        "openid": app.globalData.logininfo.openid,
        "storeremark": updatename
      };
    }
    if (openUpdate){
      wx.showLoading({
        title: atitle,
        //mask: true
      })

      util.post(api.My_fetchTokenUrl).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        //console.log("res:" + res.accesstoken);

        if (res.access_token != '') {
          _this.setData({
            accesstoken: res.access_token
          });

          let url = api.My_doUpdateStoreInfo + "?access_token=" + _this.data.accesstoken;
          util.request(url, param, 'POST').then((res2) => {
            console.log(res2);

            if (akind == 'storefullname') {
              _this.data.logininfo.storeInfo.storefullname = updatename;
            }
            else if (akind == 'zipcode') {
              _this.data.logininfo.storeInfo.zipcode = updatename;
            }
            else if (akind == 'addr') {
              _this.data.logininfo.storeInfo.addr = updatename;
            }
            else if (akind == 'mastername') {
              _this.data.logininfo.storeInfo.mastername = updatename;
            }
            else if (akind == 'jobtitle') {
              _this.data.logininfo.storeInfo.jobtitle = updatename;
            }
            else if (akind == 'mobile') {
              _this.data.logininfo.storeInfo.mobile = updatename;
            }
            else if (akind == 'storeremark') {
              _this.data.logininfo.storeInfo.storeremark = updatename;
            }

            wx.setStorage({
              key: 'logininfo',
              data: _this.data.logininfo
            });

            wx.hideLoading();
          }).catch((err) => {
            wx.hideLoading();

            console.log(err);
            console.log("保存信息错误!");
          });
        }
        else {
          console.log("error accesstoken!");
        }
      }).catch((err) => {
        wx.hideLoading();

        console.log(err);
      });
    }
  },
  /**
   * 跳转晋级VIP
   */
  gotoPromotedVIP: function () {
    wx.navigateTo({
      url: '/grade/pages/grade/promotedVIP/promotedVIP',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})